import React, { useMemo } from "react"
import { useDidShow } from "@tarojs/taro"
import { Input, View, Image, ScrollView, Text } from "@tarojs/components"
import { syncTabbarActive } from "@/utils/tabbar"
import { pageMapper, pageMapperCommunity, tabbarPages } from "@/constants/pageMap"
import GpContainer from "@/components/GpContainer"
import { Play } from "@taroify/icons"
import { useSetState, useLayout, useNavigationOpacity, useRefererMini } from "@/utils/hooks"
import GpBlock from "@/components/GpBlock"
import clsx from "clsx"
import Icon from "@/components/GpFontIcon"
import TabbarPlaceholder from "../components/TabbarPlaceholder"
import { getIndexData } from "@/apis/yikao-community"
import { MenuContentType } from "@/types/enum"
import styles from "./index.module.scss"
import { useAppDispatch, useAppSelector } from "@/store/hook"
import { requestIsFullfilled } from "@/utils/request"
import { navigation } from "@/utils/router"
import { handleBlockNavigation } from "@/utils/app"
import GpChatActionPopup from "@/components/GpChatActionPopup"
import { changeVisibility } from "@/store/actions/tabbar"

type State = {
  searchValue: string
  pageData: IApiRelative.IGetIndexData.IResData
  openChatActionPopup: boolean
  showTip: boolean
}
/**
 * @page 首页
 */
export default function Index() {
  useRefererMini()
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector(state => state.auth.userInfo)
  const [state, setState] = useSetState<State>({
    searchValue: "",
    pageData: getInitialPageData(),
    openChatActionPopup: false,
    showTip: false
  })
  const [layout] = useLayout()
  const [opacity] = useNavigationOpacity()
  const fuck = useMemo(() => {
    const menus = state.pageData.menus
    const guide1 = menus.find(l => l.type === MenuContentType.Guide1)
    const guide2 = menus.find(l => l.type === MenuContentType.Guide2)
    const guide3 = menus.find(l => l.type === MenuContentType.Guide3)
    const iconNavigations: IApiRelative.IGetIndexData.MenuItem[] = []
    const iconNavigationTypes = [
      MenuContentType.IconNavigation1,
      MenuContentType.IconNavigation2,
      MenuContentType.IconNavigation3,
      MenuContentType.IconNavigation4,
      MenuContentType.IconNavigation5
    ]
    const contentSpecials: (IApiRelative.IGetIndexData.MenuItem & { className: string })[] = []
    const contentSpecialsTypes = [
      MenuContentType.ContentSpecial1,
      MenuContentType.ContentSpecial2,
      MenuContentType.ContentSpecial3,
      MenuContentType.ContentSpecial4,
      MenuContentType.ContentSpecial5,
      MenuContentType.ContentSpecial6
    ]
    for (const menu of menus) {
      if (iconNavigationTypes.includes(menu.type)) {
        iconNavigations.push(menu)
      }
      if (contentSpecialsTypes.includes(menu.type)) {
        let className = ""
        switch (menu.type) {
          case MenuContentType.ContentSpecial1:
            className = "inner_1"
            break
          case MenuContentType.ContentSpecial2:
            className = "inner_2"
            break
          case MenuContentType.ContentSpecial3:
            className = "inner_3"
            break
          case MenuContentType.ContentSpecial4:
            className = "inner_4"
            break
          case MenuContentType.ContentSpecial5:
            className = "inner_5"
            break
          case MenuContentType.ContentSpecial6:
            className = "inner_6"
            break
          default:
            break
        }
        contentSpecials.push({
          ...menu,
          className
        })
      }
    }
    return {
      guide1,
      guide2,
      guide3,
      iconNavigations,
      contentSpecials
    }
  }, [state.pageData])
  useDidShow(() => {
    fetchData()
    syncTabbarActive(tabbarPages.index)
  })
  function getInitialPageData(): IApiRelative.IGetIndexData.IResData {
    return {
      agencys: [],
      menus: [],
      news: [],
      newsColumns: []
    }
  }
  function fetchData() {
    getIndexData().then(data => {
      if (requestIsFullfilled(data)) {
        setState({ pageData: data.data.data })
      }
    })
  }
  function handleIconNavigation(iconNavigation: IApiRelative.IGetIndexData.MenuItem) {
    handleBlockNavigation(iconNavigation)
  }
  function renderFixedTop() {
    return (
      <View
        className={styles.fixedTop}
        style={{
          backgroundColor: `rgba(255, 255, 255, ${opacity})`
        }}
      >
        {/* 状态栏 */}
        <View
          className="box-border"
          style={{
            height: layout.statusBarHeight + "px"
          }}
        ></View>
        {/* 导航栏 */}
        <View
          style={{
            height: layout.navigationHeight + "px"
          }}
          className={styles.fuckNav}
          onClick={() => navigation(pageMapperCommunity.ChooseInfo)}
        >
          <Image src="/images/yikao-community/index-location.png" className={styles.iconLocation} />
          <View className={styles.fuckTitle}>
            {userInfo.areaName}-{userInfo.projectName}
          </View>
          <Play
            size={12}
            style={{
              transform: "rotate(90deg)"
            }}
          />
        </View>

        {/* 提示 */}
        <View>
          {state.showTip && (
            <View
              className={styles.fuckTip}
              onClick={ev => {
                ev.preventDefault()
                ev.stopPropagation()
              }}
            >
              <View className={styles.fuckTipContent}>
                <View className="box-border flex flex-row items-center flex-1">
                  <Icon icon="icon-tishi" color="#FFFFFF" size={28} className="leading-48px" />
                  <View className={styles.fuckTipText}>资料显示与当前设置不符 切换到</View>
                </View>
                <View className={styles.fuckSwitch}>呼和浩特-表（导）演</View>
              </View>
              <View
                className={styles.fuckTipClose}
                onClick={ev => {
                  ev.preventDefault()
                  ev.stopPropagation()
                  setState({ showTip: false })
                }}
              >
                <Icon icon="icon-shanchu2" color="#FFFFFF" size={16} />
              </View>
            </View>
          )}
        </View>
      </View>
    )
  }
  function renderFuck() {
    const { guide1, guide2, guide3 } = fuck
    return (
      <View className={styles.fuck}>
        {/* navigation placehoder */}
        <View
          style={{
            height: layout.statusBarHeight + layout.navigationHeight + "px"
          }}
        ></View>
        {/* 搜索框 */}
        <View className={styles.searhWrapper}>
          <View className={styles.searchInput}>
            <Icon
              icon="icon-shouye-sousuo"
              color="#BBBBBB"
              size={32}
              className="text-center cursor-pointer"
            />
            <Input
              disabled
              placeholder="请输入要搜索的内容"
              value={state.searchValue}
              placeholderStyle="color: #BBBBBB;"
              style={{
                color: "#333333"
              }}
              className={styles.Input}
              onClick={() => navigation(pageMapperCommunity.HomeSearch)}
            />
          </View>
        </View>
        {/* 三巨头 */}
        <View className={styles.fuckFemaleDog}>
          <View className={styles.unknownField} onClick={() => handleBlockNavigation(guide1)}>
            <View className={styles.unknownFieldTitle}>{guide1?.name}</View>
            <View className={styles.unknownFieldDesc}>{guide1?.description}</View>
            <View className={styles.unknownFieldEntry}>{guide1?.displayName}</View>
            <View className={styles.unknownFieldImageWrapper}>
              <Image src={guide1?.image} className={styles.unknownFieldImage} />
            </View>
          </View>
          <View className={styles.unknownField1}>
            <View className={styles.guideTwo} onClick={() => handleBlockNavigation(guide2)}>
              <View className={styles.guideTwoTitle}>{guide2?.name}</View>
              <View className={styles.guideTwoImage}>
                <Image src={guide2?.image} className={styles.guideTwoImg} />
              </View>
            </View>
            <View className={styles.guideThree} onClick={() => handleBlockNavigation(guide3)}>
              <View className={styles.guideTwoTitle}>{guide3?.name}</View>
              <View className={styles.guideTwoImage}>
                <Image src={guide3?.image} className={styles.guideTwoImg} />
              </View>
            </View>
          </View>
        </View>
      </View>
    )
  }
  function renderNavigations() {
    const { iconNavigations } = fuck

    return (
      <View className={styles.navigations}>
        {iconNavigations.map(l => (
          <View className={styles.navigation} key={l.id} onClick={() => handleIconNavigation(l)}>
            <Image src={l.icon} className={styles.navigationIcon} />
            <View className={styles.navigationTitle}>{l.name}</View>
          </View>
        ))}
      </View>
    )
  }
  function renderContentSpecials() {
    const { contentSpecials } = fuck
    return (
      <ScrollView scrollX className={styles.contentSpecials}>
        {contentSpecials.map(l => (
          <View
            className={styles.contentSpecial}
            key={l.id}
            onClick={() => handleBlockNavigation(l)}
          >
            <View className={clsx(styles.inner, styles[l.className])}>
              <View className={styles.innerTitle}>{l.name}</View>
              <View className={styles.innerDesc}>{l.description}</View>
            </View>
          </View>
        ))}
      </ScrollView>
    )
  }
  function renderTodayTopic() {
    const { discussion } = state.pageData
    if (!discussion) return null
    return (
      <GpBlock
        title="今日话题"
        className={styles.blockClass}
        contentClassName={styles.topicContent}
        onArrowClick={() => navigation(pageMapperCommunity.Wordsquare)}
      >
        <View className={styles.todayTopicRight}>
          <Image
            src="https://static.91goodschool.com/UpFiles/public/yikao/image/index-dophy.png"
            className={styles.todayTopicRightImage}
          />
        </View>
        <View className={styles.todayTopic}>
          <View className={styles.todayTopicLeft}>
            <View className={styles.todayTopicTitle}>
              <Image src="/images/yikao-community/topic.png" className={styles.todayTopicIcon} />
              {discussion.title}
            </View>
            <View className={styles.topicBtns}>
              <View
                className={styles.fuckTopicBtn}
                onClick={() => {
                  dispatch(changeVisibility(false))
                  setState({ openChatActionPopup: true })
                }}
              >
                <View className={styles.topicBtn}>
                  <Text className={styles.topicBtnText}>参与</Text>
                </View>
              </View>
              <View
                className={styles.fuckTopicBtn}
                onClick={() => navigation(pageMapperCommunity.WordDetail, { id: discussion.id })}
              >
                <View className={styles.topicBtn}>
                  <Text className={styles.topicBtnText}>查看</Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      </GpBlock>
    )
  }
  function renderInstitutions() {
    const { agencys } = state.pageData
    if (agencys.length === 0) return null
    return (
      <GpBlock
        title="精选机构"
        className={styles.blockClass}
        onArrowClick={() =>
          navigation(tabbarPages.gpPluginInstitution, null, "switchTab", false, true)
        }
      >
        <ScrollView scrollX className={styles.institution}>
          {agencys.map(l => (
            <View
              className={styles.institutionItemWrap}
              key={l.id}
              onClick={() => navigation(pageMapper.institutionDetail, { id: l.id })}
            >
              <View className={styles.institutionItem}>
                <Image src={l.cover} className={styles.institutionItemImage} />
                <View className={clsx("ellipse_1", styles.institutionTitle)}>{l.name}</View>
                <View className={styles.institutionInfo}>
                  <Icon icon="icon-dingweixianxing" size={24} color="#999999" />
                  <View className="truncate">{l.address}</View>
                </View>
              </View>
            </View>
          ))}
        </ScrollView>
      </GpBlock>
    )
  }
  function renderNews() {
    const { news } = state.pageData
    return (
      <GpBlock
        title="最新资讯"
        className={styles.blockClass}
        onArrowClick={() => navigation(pageMapper.news)}
      >
        <ScrollView scrollX className={styles.newsScroll}>
          <View className={clsx(styles.newsItemWrap, styles.newsItem_active)}>
            <View className={styles.newsItem}>推荐</View>
          </View>
          {/* {newsColumns.map(l => (
            <View className={styles.newsItemWrap} key={l.value} onClick={() => }>
              <View className={styles.newsItem}>{l.label}</View>
            </View>
          ))} */}
          <View className={styles.newsItemWrap} onClick={() => navigation(pageMapper.examDynamic)}>
            <View className={styles.newsItem}>艺考动态</View>
          </View>
          <View className={styles.newsItemWrap} onClick={() => navigation(pageMapper.examQA)}>
            <View className={styles.newsItem}>艺考问答</View>
          </View>
          <View className={styles.newsItemWrap} onClick={() => navigation(pageMapper.trainGuide)}>
            <View className={styles.newsItem}>培训指南</View>
          </View>
          <View className={styles.newsItemWrap} onClick={() => navigation(pageMapper.examStrategy)}>
            <View className={styles.newsItem}>艺考政策</View>
          </View>
        </ScrollView>
        <View className={styles.newsList}>
          {news.map(l => (
            <View
              className={styles.listItem}
              key={l.id}
              onClick={() => navigation(pageMapper.newsDetail, { id: l.id })}
            >
              <Image src={l.picture} className={styles.listItemImage} mode="aspectFill" />
              <View className={styles.listItemInfo}>
                <View className={styles.listItemTitle}>{l.title}</View>
                <View className={styles.listItemDesc}>
                  <View>{l.updatedBy}</View>
                  <View>{l.updatedRelativeTime}</View>
                </View>
              </View>
            </View>
          ))}
          {/* <View className={styles.noMoreTip}>-没有更多了-</View> */}
        </View>
      </GpBlock>
    )
  }
  function renderChatActionPopup() {
    return (
      <GpChatActionPopup
        open={state.openChatActionPopup}
        closeFn={() => {
          setState({ openChatActionPopup: false })
          dispatch(changeVisibility(true))
        }}
        topicId={state.pageData.discussion?.id as number}
      />
    )
  }
  return (
    <GpContainer
      pageGap={112}
      style={{
        backgroundColor: "#ffffff",
        "--navH": layout.statusBarHeight + layout.navigationHeight + "px"
      }}
    >
      <TabbarPlaceholder>
        <View className="relative z-50 bgBox bgBox1">
          {renderFixedTop()}
          {renderFuck()}
          {renderNavigations()}
          {renderContentSpecials()}
          {renderTodayTopic()}
          {/* {renderInstitutions()} */}
          {renderNews()}
          {renderChatActionPopup()}
        </View>
      </TabbarPlaceholder>
    </GpContainer>
  )
}
